package com.cc.satoken;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollectionUtil;
import com.cc.enums.RedisEnmu;
import com.cc.mapper.RoleMapper;
import com.cc.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义权限加载接口实现类
 *
 * @author shadow
 */
@Component    // 保证此类被 SpringBoot 扫描，完成 Sa-Token 的自定义权限验证扩展
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        List<String> permissionList = new ArrayList<>();
        //根据角色roleKey查询所有权限标识
        for (String roleKey : getRoleList(loginId, loginType)) {
            //从redis查询数据
            List<String> permits = (List<String>) SaManager.getSaTokenDao().getObject(RedisEnmu.SATOKEN_ROLE_FIND_PERMISSION + roleKey);
            if (CollectionUtil.isEmpty(permits)) {
                // 从数据库查询这个角色所拥有的权限列表
                permits = roleMapper.getPermissionsKeyByRoleKey(roleKey);
                // 查好后，set 到缓存中
                SaManager.getSaTokenDao().setObject(RedisEnmu.SATOKEN_ROLE_FIND_PERMISSION + roleKey, permits, RedisEnmu.TIMEOUT);
            }
            permissionList.addAll(permits);
        }
        return permissionList;
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        List<String> roleList = (List<String>) SaManager.getSaTokenDao().getObject(RedisEnmu.SATOKEN_LOGIN_ID_FIND_ROLE + loginId);
        if (CollectionUtil.isEmpty(roleList)) {
            //根据用户id查询所有用户角色标识
            roleList = userMapper.getRoleKeyByUserId(loginId);
            // 查好后，set 到缓存中
            SaManager.getSaTokenDao().setObject(RedisEnmu.SATOKEN_LOGIN_ID_FIND_ROLE + loginId, roleList, RedisEnmu.TIMEOUT);
        }
        return roleList;
    }
}
